﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using Cms.Application;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Domain;
using Cms.Web.Framework.Controls;
using Cms.Web.UI.Admin.HelperClasses;
using iLib.Web.UI;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Cms.Web.UI.Admin
{
    public partial class EditContent : AdminPage, IEditContentView
    {
        private EditContentPresenter _presenter;


        private string SaveReturnUrl
        {
            get { return (string) ViewState["SaveReturnUrl"]; }
            set { ViewState["SaveReturnUrl"] = value; }
        }


        private string CancelReturnUrl
        {
            get { return (string) ViewState["CancelReturnUrl"]; }
            set { ViewState["CancelReturnUrl"] = value; }
        }

        #region IEditContentView Members

        public string CurrentTab
        {
            get { return tabStrip.CurrentValue; }
        }


        public int CurrentContentID
        {
            get
            {
                if (ViewState["CurrentContentID"] != null)
                    return int.Parse(ViewState["CurrentContentID"].ToString());
                else
                    return -1;
            }
            set { ViewState["CurrentContentID"] = value; }
        }


        public int MasterTemplateID
        {
            get { return QueryString.GetInt32ID("MasterTemplateID"); }
        }


        public int DetailTemplateID
        {
            get { return QueryString.GetInt32ID("DetailTemplateID"); }
        }


        public int PageID
        {
            get { return QueryString.GetInt32ID("PageID"); }
        }


        public int ContentID
        {
            get { return QueryString.GetInt32ID("ContentID"); }
        }


        public string AreaID
        {
            get { return Request.QueryString["AreaID"]; }
        }


        public int LocaleID
        {
            get { return QueryString.GetInt32ID("LocaleID"); }
        }


        public int VersionID
        {
            get { return QueryString.GetInt32ID("VersionID"); }
        }


        public string ContextTranslationFile
        {
            get { return "Admin/Translations/EditContent.xml"; }
        }


        public string Content
        {
            get { return txtContent.Text; }
            set { txtContent.Text = value; }
        }


        public string ContentTitle
        {
            get { return txtTitle.Text; }
            set { txtTitle.Text = value; }
        }


        public void SetHeaderContentDescription(string value)
        {
            if (value != null)
                HeadingText = GetText(this, "EditContentHeading") + " &mdash; " + value;
            else
                HeadingText = GetText(this, "NewContentHeading");
        }


        public string Name
        {
            get { return txtName.Text; }
            set { txtName.Text = value; }
        }


        public void SetCategories(IList<Category> rootCategories, IList<Category> inheritedCategories,
                                  IList<Category> categories)
        {
            csCategories.SetCategories(rootCategories, inheritedCategories, categories);
            trCategories.Visible = rootCategories.Count > 0;
        }


        public IEnumerable<Category> GetSelectedCategories()
        {
            return csCategories.GetSelectedCategories();
        }


        public string SortKey
        {
            get { return txtSortKey.Text; }
            set { txtSortKey.Text = value; }
        }


        public int SelectedCategoryID
        {
            get { return QueryString.GetInt32ID("SelectedCategory"); }
        }


        public void SetAllowedAdministratorGroups(IList<AdministratorGroup> availableGroups,
                                                  IList<AdministratorGroup> inheritedGroups,
                                                  IList<AdministratorGroup> groups)
        {
            gsAllowedAdministratorGroups.SetGroups(availableGroups, inheritedGroups, groups);
            trAllowedAdministratorGroups.Visible = availableGroups.Count > 0;
        }


        public IEnumerable<AdministratorGroup> GetSelectedAllowedAdministratorGroups()
        {
            return gsAllowedAdministratorGroups.GetSelectedGroups();
        }


        public void SetDeniedAdministratorGroups(IList<AdministratorGroup> availableGroups,
                                                 IList<AdministratorGroup> inheritedGroups,
                                                 IList<AdministratorGroup> groups)
        {
            gsDeniedAdministratorGroups.SetGroups(availableGroups, inheritedGroups, groups);
            trDeniedAdministratorGroups.Visible = availableGroups.Count > 0;
        }


        public IEnumerable<AdministratorGroup> GetSelectedDeniedAdministratorGroups()
        {
            return gsDeniedAdministratorGroups.GetSelectedGroups();
        }


        public void SetRequiredUserGroups(IList<UserGroup> availableGroups, IList<UserGroup> inheritedGroups,
                                          IList<UserGroup> selectedGroups, IList<UserGroup> deselectedGroups)
        {
            gsRequiredUserGroups.SetGroups(availableGroups, inheritedGroups, selectedGroups, deselectedGroups);
            trRequiredUserGroups.Visible = availableGroups.Count > 0;
        }


        public IEnumerable<UserGroup> GetSelectedRequiredUserGroups()
        {
            return gsRequiredUserGroups.GetSelectedGroups();
        }


        public IEnumerable<UserGroup> GetDeselectedUserGroups()
        {
            return gsRequiredUserGroups.GetDeselectedGroups();
        }


        public DateTime? StartPublishing
        {
            get
            {
                if (string.IsNullOrEmpty(txtStartPublishing.Text.Trim()))
                    return null;
                return DateTime.Parse(txtStartPublishing.Text);
            }
            set
            {
                txtStartPublishing.Text = value.HasValue
                                              ? value.Value.ToShortDateString() + " " + value.Value.ToShortTimeString()
                                              : "";
            }
        }


        public DateTime? EndPublishing
        {
            get
            {
                if (string.IsNullOrEmpty(txtEndPublishing.Text.Trim()))
                    return null;
                return DateTime.Parse(txtEndPublishing.Text);
            }
            set
            {
                txtEndPublishing.Text = value.HasValue
                                            ? value.Value.ToShortDateString() + " " + value.Value.ToShortTimeString()
                                            : "";
            }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            if (Request.QueryString.Count == 0)
                Response.Redirect("Explorer.aspx");
            base.OnLoad(e);
            _presenter = new EditContentPresenter(this);
            if (!Page.IsPostBack)
            {
                if (ContentID == -2)
                {
                    // New content
                    tabStrip.SelectedValue = "properties";
                    HeadingIcon = "Admin/Img/Icons/page_white_add.png";
                    lbContinue.Visible = true;
                    lbSave.Attributes.CssStyle.Add("display", "none");
                    txtName.Focus();
                }
                else
                {
                    lbContinue.Visible = false;
                    HeadingIcon = "Admin/Img/Icons/page_white_edit.png";
                }
                _presenter.Initialize();
                SaveReturnUrl = Request.QueryString["SaveReturnUrl"];
                CancelReturnUrl = Request.QueryString["CancelReturnUrl"];
            }
            tiProperties.OnClientClick =
                "cms.Edit.ShowTabOverlays(); if (isDirty()) return cms.Dialogs.ConfirmLinkButton(this, " +
                "function (status) { if (status != 'ok') cms.Edit.HideTabOverlays(); }, " +
                "'" + GetText(this, "SaveInfoHeader") + "', " +
                "'" + GetText(this, "SaveInfoMessage") + "', " +
                "'" + GetText(this, "SaveInfoOK") + "', " +
                "'" + GetText(this, "SaveInfoCancel") + "', " +
                "true, " +
                "null);";
            tiContent.OnClientClick = tiProperties.OnClientClick;
        }


        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);

            IDiskAccess DiskAccess = new DiskAccess();
            object commonJSON =
                JsonConvert.DeserializeObject(DiskAccess.ReadTextFile("Admin\\Resources\\Common-TinyMCE-JSON-Config.js"));
            object customerJSON =
                JsonConvert.DeserializeObject(DiskAccess.ReadTextFile("Admin\\Resources\\Customer-TinyMCE-JSON-Config.js")) ??
                new JObject();
            var mergedJSON = new JObject();
            foreach (JProperty property in ((JObject) commonJSON).Children())
                mergedJSON[property.Name] = property.Value;
            foreach (JProperty property in ((JObject) customerJSON).Children())
                mergedJSON[property.Name] = property.Value;
            string script = "<script type=\"text/javascript\" language=\"javascript\">" + Environment.NewLine;
            script += "tinyMCE.init(" + Environment.NewLine;
            script += JsonConvert.SerializeObject(mergedJSON, Formatting.Indented);
            script += Environment.NewLine + ");" + Environment.NewLine;
            script += DiskAccess.ReadTextFile("Admin\\Resources\\Common-TinyMCE-Init.js") + Environment.NewLine;
            script += DiskAccess.ReadTextFile("Admin\\Resources\\Customer-TinyMCE-Init.js") + Environment.NewLine;
            script += "</script>";
            string spellcheckerLanguages;
            switch (Localization)
            {
                case "sv-SE":
                    script = script.Replace("[[Language]]", "sv");
                    spellcheckerLanguages =
                        "Engelska=en,Danska=da,Holländska=nl,Finska=fi,Franska=fr,Tyska=de,Italienska=it,Polska=pl,Portugisiska=pg,Spanska=es,+Svenska=sv";
                    break;
                default:
                    script = script.Replace("[[Language]]", "en");
                    spellcheckerLanguages =
                        "+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pg,Spanish=es,Swedish=sv";
                    break;
            }
            script = script.Replace("[[SpellcheckerLanguages]]", spellcheckerLanguages)
                .Replace("[[Stylesheets]]", _presenter.GetStylesheets(Request.QueryString["editorbodywidth"]))
                .Replace("[[FullPath]]", Url.FullPath)
                .Replace("[[FileBrowser]]", GetText(this, "FileBrowserHeader"))
                .Replace("[[BaseUrl]]", Url.FullPath)
                .Replace("[[LocaleID]]", LocaleID.ToString())
                .Replace("[[HtmlDesignTemplatesIndexFile]]",
                         "/Admin/Resources/HtmlDesignTemplates.js?v=" + DateTime.Now.Ticks);
            Header.Controls.Add(new LiteralControl(script));
            ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(),
                                                            "updatePanels",
                                                            "updatePanels('" + tabStrip.SelectedValue + "');", true);
            upnlProperties.Update();
            Page.Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">" +
                                                        DatePickerHelper.GetDatePickerSetup(Localization) +
                                                        "</script>"));
        }


        protected void tabStrip_Click(string value)
        {
            if (CurrentTab == "properties")
                _presenter.Save();
            if (!_presenter.IsValid)
                return;
            lbContinue.Visible = false;
            lbSave.Attributes.CssStyle.Add("display", "inline");
            ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(), "init", "init(); updateButtons();",
                                                            true);
        }


        protected void lbContinue_Click(object sender, EventArgs e)
        {
            if (CurrentTab == "properties")
                _presenter.Save();
            if (!_presenter.IsValid)
                return;
            ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(), "init", "init();", true);
            tabStrip.SelectedValue = "content";
            lbContinue.Visible = false;
            lbSave.Attributes.CssStyle.Add("display", "inline");
            upnlTabs.Update();
        }


        protected void lbSave_Click(object sender, EventArgs e)
        {
            int versionID = _presenter.Save();
            if (!_presenter.IsValid)
                return;
            string returnUrl = SaveReturnUrl;
            if (returnUrl.ToLower() == "editcontentpreview.aspx?id=-2")
                returnUrl = returnUrl.Replace("-2", CurrentContentID.ToString());
            Response.Redirect(returnUrl + "&versionid=" + versionID);
        }


        protected void lbCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(CancelReturnUrl);
        }
    }
}